package com.scs.application.core.mvc.validation.validators;

import com.scs.application.core.mvc.validation.constraints.Mobile;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.invoke.MethodHandles;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @Description:
 */
public class MobileValidator implements ConstraintValidator<Mobile, CharSequence> {
    private static final Log LOG = LoggerFactory.make(MethodHandles.lookup());

    private java.util.regex.Pattern pattern;

    private final Pattern LOCAL_PART_PATTERN = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$");


    @Override
    public void initialize(Mobile mobileAnnotation) {

        // we only apply the regexp if there is one to apply
        if (!".*".equals(mobileAnnotation.regexp())) {
            try {
                pattern = java.util.regex.Pattern.compile(mobileAnnotation.regexp());
            } catch (PatternSyntaxException e) {
                throw LOG.getInvalidRegularExpressionException(e);
            }
        }else {
            pattern = LOCAL_PART_PATTERN;
        }
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        if (pattern == null) {
            return false;
        }
        Matcher m = pattern.matcher(value);
        return m.matches();
    }
}
